import { createDictType, updateDictType } from "@/services/mainten/api";
import {
  ModalForm,
  ProForm,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea
} from "@ant-design/pro-components";
import dayjs from 'dayjs';
import { message } from "antd";
import React, { useState, useEffect } from "react";
import { useIntl } from "umi";
import { DictTypeVo } from "../../constants"



interface CreateModalProps {
  visible: boolean;
  values?: DictTypeVo;
  onCancel: () => void;
  onSuccess: () => void;
}
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const AddForm: React.FC<CreateModalProps> = ({
  visible,
  values,
  onCancel,
  onSuccess,
}) => {
  const [form] = ProForm.useForm<DictTypeVo>();
  const intl = useIntl();
  const [validPeriodDateFor, setValidPeriodDateFor] = useState<string>('');
  const [validPeriodDateTo, setValidPeriodDateTo] = useState<string>('');
  // const [updateStatus, setUpdateStatus] = useState<boolean>(false);
  const [editStatus, setEditStatus] = useState<boolean>(false);


  useEffect(() => {
    if (visible) {   
      if(values){
        console.log("address:"+JSON.stringify(values));
        setEditStatus(true);
        values.status = String(values.status);
      } 
      form.setFieldsValue(values || {});
    }
  }, [visible, values]);


  const handleSubmit = async (formValues: DictTypeVo) => {
    //  console.log("customer1:" + JSON.stringify(values));
    if (values?.id) {
      formValues.id=values?.id;
      // formValues.customerId = values?.customerId;
      // formValues.customerCode = values?.customerCode;
      return await handleUpdateCustomer(formValues);
    }
    try {
      // API调用逻辑
      const response = await createDictType(formValues);

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.operating" }));
        } else {
          // throw new Error(response.msg);
          message.error(response.msg);
          return false;
        }
      }
      message.success(intl.formatMessage({ id: "request.success.operating" }));
      onSuccess();
      form.resetFields();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };

  const handleUpdateCustomer = async (updateData: DictTypeVo) => {
    try {
      // API调用逻辑    

      const response = await updateDictType(updateData.id,updateData);

      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.operating" }));
        } else {
          // throw new Error(response.msg);
          message.error(response.msg);
          return false;
        }
      }
      message.success(intl.formatMessage({ id: "request.success.operating" }));
      onSuccess();
      form.resetFields();
      return true;
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  }

  const handleValuesChange = (changedValues, allValues) => {
    // changedValues 是发生变化的字段
    // allValues 是表单当前所有的值
    // console.log(changedValues);
  };

   const closeModel = ()=>{
    form.resetFields;
    onCancel();
  }

  return (
    <ModalForm<DictTypeVo>
      title={values?.id
                ? intl.formatMessage({ id: 'pages.edit' })
                : intl.formatMessage({ id: 'pages.create' })}
      width="40%"
      form={form}
      open={visible}
      onOpenChange={(visible) => !visible && closeModel()}
      onFinish={handleSubmit}
      onValuesChange={handleValuesChange} // 监听值变化
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        searchConfig: {
          submitText: intl.formatMessage({ id: "pages.button.submit" }),
          resetText: intl.formatMessage({ id: "pages.button.cancel" }),
        },
      }}
      layout="horizontal"
      {...formItemLayout}
    >
      {/* 单列布局 - 移除了所有 ProForm.Group */}
      {/* <ProForm.Group></ProForm.Group>  */}
      <ProFormText
        name="name"
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.dict.name", defaultMessage:"Dictionary Name"
        })}
        placeholder={intl.formatMessage({
          id: "pages.dict.name", defaultMessage:"Dictionary Name"
        })}        
        rules={[{ required: true, message: intl.formatMessage({
          id: "pages.dict.name.required", defaultMessage:"Required Dictionary Name"
        }) }]}
      />

      <ProFormText
        name="type"
        disabled={editStatus}
        colProps={{ md: 12, xl: 8 }}
        label={intl.formatMessage({
          id: "pages.dict.type",defaultMessage:"Dictionary Type"
        })}
        placeholder={intl.formatMessage({
          id: "pages.dict.type",defaultMessage:"Dictionary Type"
        })}
        rules={[{ required: true, message: intl.formatMessage({
          id: "pages.dict.type.required", defaultMessage:"Required Dictionary Type"
        })}]}
      />

      <ProFormRadio.Group
        name="status"
        label={intl.formatMessage({
          id: "pages.status",
          defaultMessage:"Status",
        })}
        rules={[{ required: true }]}
        initialValue="0"
        options={[
          {
            label: intl.formatMessage({ id: 'pages.active' }),
            value: '0',
          },
          {
            label: intl.formatMessage({ id: 'pages.inactive' }),
            value: '1',
          },
        ]}
      />
      <ProFormTextArea 
        name="remark"
        label={intl.formatMessage({
          id: "pages.dict.remark",
          defaultMessage:"Remark",
        })}
        placeholder={intl.formatMessage({
          id: "pages.dict.remark",
          defaultMessage:"Remark",
        })}
        // rules={[{ required: true, message: "请输入州" }]}
      />
    </ModalForm>
  );
};

export default AddForm;
